import React, { Component } from 'react';
import { Form, Input, Button, Modal, Col, Row, Upload, DatePicker, message, Select, Tag, Tooltip, TreeSelect } from 'antd';
import { MinusCircleOutlined, PlusOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { connect } from "dva"
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import styles from './create.less';
import moment from 'moment'
import * as requesturl from "@/services/request-url";

const { TextArea } = Input
const { Option } = Select

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
@connect()
class CreateForm extends Component {
  constructor(props) {
    super(props);
    // this.htmlstring = `<p>我一开始就存在哦</p>`
    this.state = {
      editorState: BraftEditor.createEditorState(null),//富文本
      imgUrls: [],//图片
      form: {},//表单数据
      addTime: "",
      releaseTime: "",
      loading: false,
      previewVisible: false,
      previewImage: '',
      previewTitle: '',
      fileList: [],//已有图片
      initvalue: [""],//文献已有数据
      formloading: false,
      typeList: [//类别
        { id: 1, name: "类别1" },
        { id: 2, name: "类别2" }
      ],
      tags: [],//关键字
      inputVisible: false,
      inputValue: '',
      editInputIndex: -1,
      editInputValue: '',
      uploadFileList: [],//上传附件列表
    }
  }
  //关键字标签
  handleClose = removedTag => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    console.log(tags);
    this.setState({ tags });
  };

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  };

  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };

  handleInputConfirm = () => {
    const { inputValue } = this.state;
    let { tags } = this.state;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      tags = [...tags, inputValue];
    }
    console.log(tags);
    this.setState({
      tags,
      inputVisible: false,
      inputValue: '',
    });
  };

  handleEditInputChange = e => {
    this.setState({ editInputValue: e.target.value });
  };

  handleEditInputConfirm = () => {
    this.setState(({ tags, editInputIndex, editInputValue }) => {
      const newTags = [...tags];
      newTags[editInputIndex] = editInputValue;

      return {
        tags: newTags,
        editInputIndex: -1,
        editInputValue: '',
      };
    });
  };

  saveInputRef = input => {
    this.input = input;
  };

  saveEditInputRef = input => {
    this.editInput = input;
  };

  //上传附件
  handleFileUpload = ({ file, fileList }) => {
    if(file.response&&file.response.code==="403"){
      let a = document.createElement("a")
      a.href = `${requesturl.login}/cas/jwt/login.do`;
      a.click();
  }
    if (file.status !== 'uploading') {
      console.log(file.response, fileList);
    }
    if (file.status === 'done') {
      this.setState({
        uploadFileList: [
          // ...this.state.uploadFileList,
          {
            uid: new Date(),
            name: '附件',
            status: 'done',
            url: file.response.data,
          },
        ]
      })
    }
    else if (file.status === 'removed') {
      console.log(fileList)
      this.setState({
        uploadFileList: fileList
      })
    }
  }
  //上传图片
  handleCancelImg = () => this.setState({ previewVisible: false });
  handleChangeImg = ({ file, fileList }) => {
    if(file.response&&file.response.code==="403"){
      let a = document.createElement("a")
      a.href = `${requesturl.login}/cas/jwt/login.do`;
      a.click();
  }
    console.log(file, file.status)
    console.log(fileList)
    console.log(this.state.imgUrls)
    if (file.status === "done") {
      console.log(fileList)
      this.setState({
        imgUrls: [...this.state.imgUrls, file.response.data],
      })

    } else if (file.status === "removed") {
      console.log(fileList, file)
      let arr = []
      fileList.map(item => {
        arr.push(item.url)
      })
      console.log(arr)
      this.setState({
        imgUrls: arr
      })
    }
    this.setState({ fileList })
  };
  //点击图片
  handlePreview = async file => {
    console.log(file)
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  componentDidMount = () => {
    this.getTypeTree()
    const { softwareDetail } = this.props
    console.log(softwareDetail)
    this.setState({
      fileList: []
    })
    softwareDetail.addTime = softwareDetail.addTime ? moment(softwareDetail.addTime) : ""
    softwareDetail.releaseTime = softwareDetail.releaseTime ? moment(softwareDetail.releaseTime) : ""
    // console.log(softwareDetail.imgUrls.split(","))
    if(softwareDetail.source){
      this.setState({
        initvalue:softwareDetail.source.split(",")
      })
    }
    if (softwareDetail.keys) {//处理关键词回显
      this.setState({
        tags: softwareDetail.keys.split(","),
      })
    }
    if (softwareDetail.attachment) {//处理文件回显
      let attachmentlist = []
      softwareDetail.attachment.split(",").map((item, index) => {
        let itemarr = item.split("/")
        let obj = {
          uid: index * -20,
          name: itemarr[itemarr.length - 1],
          status: 'done',
          url: item,
        }
        attachmentlist.push(obj)
      })
      this.setState({
        uploadFileList: attachmentlist
      })
    }
    if (softwareDetail.imgUrls) {//处理图片回显
      let filelist = []
      softwareDetail.imgUrls.split(",").map((item, index) => {
        let itemarr = item.split("/")
        let obj = {
          uid: index * -1,
          name: itemarr[itemarr.length - 1],
          status: 'done',
          url: item,
        }
        filelist.push(obj)
      })
      this.setState({
        fileList: filelist,
        imgUrls: softwareDetail.imgUrls.split(",")
      })
    }
    this.setState({
      editorState: BraftEditor.createEditorState(softwareDetail.content),
      initvalue: softwareDetail.source ? softwareDetail.source.split(",") : [""],
      form: {
        ...softwareDetail,
      },

      formloading: true
    })
  }
  getTypeTree = () => {
    this.props.dispatch({
      type: "global/getDirs",
      payload: {

      }
    }).then(res => {
      console.log(res)
      if (res) {
        res.data.map(item => {
          item.value = item.code
          item.title = item.name
          item.disabled = true
          if (item.children.length > 0) {
            item.children.map(item2 => {
              item2.value = item2.code
              item2.title = item2.name
            })
          }
        })
        this.setState({
          typeList: res.data
        })
      }
    })
  }
  //类别选择
  handleTypeChange = (value) => {
    console.log(value)
    this.setState({
      form: {
        ...this.state.form,
        type: value
      }
    })
  }

  handleChange = (editorState) => {
    this.setState({ editorState })
    console.log(editorState)
  }
  //表单值发生变化
  handleValuesChange = (changeValue, allValue) => {
    console.log(allValue)
    allValue.names.toString()
    this.setState({ form: allValue })
  }
  //验证成功
  submit = () => {
    this.setState({
      loading: true
    })
    let { form, addTime, releaseTime, editorState, imgUrls, tags, uploadFileList } = this.state
    this.props.handleOk()
    console.log(uploadFileList)
    console.log(this.state.form)
    console.log(this.state.editorState)
    console.log(this.state.initvalue)
    let attachmentUrl = []
    uploadFileList.map((item, index) => {
      attachmentUrl.push(item.url)
    })
    this.props.dispatch({
      type: "global/saveKnowledge",
      payload: {
        ...form,
        keys: tags.join(","),
        addTime: form.addTime ? form.addTime : addTime,
        releaseTime: form.releaseTime ? form.releaseTime : releaseTime,
        id: this.props.softwareDetail.id,
        source: form.names&&form.names.length>0 ? form.names.join(",") : "",
        attachment: attachmentUrl.join(","),//附件
        imgUrls: imgUrls.join(","),
        content: editorState ? editorState.toHTML() : BraftEditor.createEditorState(null)//富文本
      }
    }).then(res => {
      console.log(res)
      if (res) {
        this.props.getSoftWareList()
        message.success("更新成功！")
        this.setState({
          loading: false
        })
      }
    })

  }
  //验证失败
  onFinishFailed = (params) => {
    this.setState({
      loading: false
    })
    message.warning("请填写完整！")
  }

  //保存 取消
  handleCancel = () => {
    this.props.handleCancel()
  }


  render() {
    let { form, loading, initvalue, editorState, fileList, previewVisible, previewTitle, previewImage, tags, inputVisible, inputValue, editInputIndex, editInputValue } = this.state;

    const uploadButton = (
      <div>
        <PlusOutlined />
      </div>
    );
    //文献动态增加内容
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 50, offset: 0 },
        sm: { span: 20, offset: 4 },
      },
    };

    return (
      <div>
        {
          this.state.formloading ?
            <Form
              name="form"
              initialValues={form}
              autoComplete="off"
              labelAlign="right"
              onFinish={this.submit}
              onFinishFailed={this.onFinishFailed}
              scrollToFirstError={true}
              onValuesChange={this.handleValuesChange}
            >
              <div style={{ background: "#F2F2F2", padding: "20px" }}>
                <div style={{ marginTop: "10px", background: "white" }}>
                  <div style={{ height: "10px" }}></div>
                  <div className={styles.formItem}>
                    <Row gutter={200}>
                      <Col span={22} offset={1}>
                        <Form.Item name="type" label="类别"
                          rules={[{ required: true, message: '请输入类别', },]}>
                          <TreeSelect treeDefaultExpandAll placeholder="请选择类别" value={form.type} treeData={this.state.typeList} onChange={this.handleTypeChange} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </div>
                </div>
                <div style={{ marginTop: "10px", background: "white" }}>
                  <div style={{ height: "10px" }}></div>
                  <div className={styles.formItem}>
                    <Row gutter={200}>
                      <Col span={22} offset={1}>
                        <Form.Item name="title" label="标题"
                          rules={[{ required: true, message: '请输入标题', },]}>
                          <Input placeholder="请输入标题" value={form.title} />
                        </Form.Item>
                        <Form.Item name="subtitle" label="副标题"
                          rules={[{ required: true, message: '请输入副标题', },]}>
                          <Input placeholder="请输入副标题" value={form.subtitle} />
                        </Form.Item>
                        <Form.Item name="desc" label="摘要"
                          rules={[{ required: true, message: '请输入摘要', },]}>
                          <TextArea placeholder="请输入摘要" rows={5} value={form.desc} maxLength={200} showCount />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={200}>
                      <Col span={11} offset={1}>
                        <Form.Item name="author" label="拥有者"
                          rules={[{ required: true, message: '请输入拥有者', },]}>
                          <Input placeholder="请输入拥有者" value={form.author} />
                        </Form.Item>
                      </Col>
                      <Col span={11}>
                        <Form.Item name="belongUnit" label="软件所属单位"
                          rules={[{ required: true, message: '请输入所属单位', },]}>
                          <Input placeholder="请输入所属单位" value={form.belongUnit} />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={200}>
                      <Col span={11} offset={1}>
                        <Form.Item name="addTime" label="添加时间"
                          rules={[{ required: true, message: '请选择添加时间', },]}>
                          <DatePicker placeholder="请选择添加时间"
                            style={{ width: "100%" }}
                            onChange={(date, dateString) => { this.setState({ addTime: dateString }) }} />
                        </Form.Item>
                      </Col>
                      <Col span={11}>
                        <Form.Item name="releaseTime" label="发布时间"
                          rules={[{ required: true, message: '请选择发布时间', },]}>
                          <DatePicker placeholder="请选择发布时间"
                            style={{ width: "100%" }}
                            onChange={(date, dateString) => { this.setState({ releaseTime: dateString }) }} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </div>
                </div>
                <div style={{ marginTop: "10px", background: "white" }}>
                  <div style={{ height: "10px" }}></div>
                  <div className={styles.formItem}>
                    <Row gutter={200}>
                      <Col span={22} offset={1}>
                        <Form.Item label="图片" >
                          <Upload
                            action={`http://${window.location.host}/api/jyk/file/upload`}
                            headers={{'p-user-token':sessionStorage.getItem("token")}}
                            listType="picture-card"
                            multiple={true}
                            fileList={fileList}
                            onPreview={this.handlePreview}
                            onChange={this.handleChangeImg}
                          >
                            {fileList.length >= 5 ? null : uploadButton}
                          </Upload>
                          <Modal
                            visible={previewVisible}
                            title={previewTitle}
                            footer={null}
                            onCancel={this.handleCancelImg}
                          >
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                          </Modal>
                        </Form.Item>
                      </Col>
                    </Row>
                  </div>
                </div>
                <div style={{ marginTop: "10px", background: "white" }}>
                  <div style={{ height: "10px" }}></div>
                  <div className={styles.formItem}>
                    <Row gutter={200}>
                      <Col span={11} offset={1}>
                        <Form.Item label="访问量" name="visitNum"
                          rules={[{ required: true, message: '请输入访问量', },]}>
                          <Input placeholder="请输入访问量" value={form.visitNum} />
                        </Form.Item>
                      </Col>
                      <Col span={11} >
                        <Form.Item label="下载量" name="downloadNum"
                          rules={[{ required: true, message: '请输入下载量', },]}>
                          <Input placeholder="请输入下载量" value={form.downloadNum} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </div>
                </div>
                <div style={{ marginTop: "10px", background: "white" }}>
                  <div style={{ height: "10px" }}></div>
                  <div className={styles.formItem}>
                    <Row gutter={200}>
                      <Col span={11} offset={1}>
                        <Form.Item label="关键词" name="keys">
                          {
                            tags.map((tag, index) => {
                              if (editInputIndex === index) {
                                return (
                                  <Input
                                    ref={this.saveEditInputRef}
                                    key={tag}
                                    size="small"
                                    className="tag-input"
                                    value={editInputValue}
                                    onChange={this.handleEditInputChange}
                                    onBlur={this.handleEditInputConfirm}
                                    onPressEnter={this.handleEditInputConfirm}
                                  />
                                );
                              }

                              const isLongTag = tag.length > 20;

                              const tagElem = (
                                <Tag
                                  className="edit-tag"
                                  key={tag}
                                  color="green"
                                  closable
                                  onClose={() => this.handleClose(tag)}
                                >
                                  <span
                                    onDoubleClick={e => {
                                      if (index !== 0) {
                                        this.setState({ editInputIndex: index, editInputValue: tag }, () => {
                                          this.editInput.focus();
                                        });
                                        e.preventDefault();
                                      }
                                    }}
                                  >
                                    {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                                  </span>
                                </Tag>
                              );
                              return isLongTag ? (
                                <Tooltip title={tag} key={tag}>
                                  {tagElem}
                                </Tooltip>
                              ) : (
                                tagElem
                              );
                            })
                          }
                          {
                            inputVisible && (
                              <Input
                                ref={this.saveInputRef}
                                type="text"
                                size="small"
                                className="tag-input"
                                value={inputValue}
                                onChange={this.handleInputChange}
                                onBlur={this.handleInputConfirm}
                                onPressEnter={this.handleInputConfirm}
                              />
                            )
                          }
                          {!inputVisible && (
                            <Tag className="site-tag-plus" onClick={this.showInput}>
                              <PlusOutlined />
                            </Tag>
                          )}

                        </Form.Item>
                      </Col>
                      <Col span={11} >
                        <Form.Item label="上传附件">
                          <Upload maxCount={1} headers={{'p-user-token':sessionStorage.getItem("token")}} action={`http://${window.location.host}/api/jyk/file/upload`} onChange={this.handleFileUpload} defaultFileList={this.state.uploadFileList}>
                            <Button type="primary" style={{ width: "100%" }}>上传附件</Button>
                            {
                              this.state.uploadFileList.length === 0 ? "暂无附件" : null
                            }
                          </Upload>
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={200}>
                      <Col span={11} offset={1}>
                        <Form.Item name="platform" label="适用平台"
                          rules={[{ required: true, message: '请输入适用平台', },]}>
                          <Input placeholder="请输入适用平台" value={form.platform} />
                        </Form.Item>
                      </Col>
                      <Col span={11}>
                        <Form.Item name="fileSize" label="文件大小"
                          rules={[{ required: true, message: '请输入文件大小', },]}>
                          <Input placeholder="请输入文件大小" value={form.fileSize} suffix="MB" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </div>
                </div>
                <div style={{ marginTop: "10px", background: "white" }}>
                  <div style={{ height: "10px" }}></div>
                  <div className={styles.formItem}>
                    <Row gutter={200}>
                      <Col span={22} offset={1}>
                        <Form.Item label="内容">
                          <div style={{ background: "#EFFBFB", margin: "10px" }}>
                            <BraftEditor
                              value={editorState}
                              placeholder="请输入文章内容"
                              onChange={this.handleChange}
                            // controls={ controlsdata }
                            // extendControls={  } 
                            />
                          </div>
                        </Form.Item>
                      </Col>
                    </Row>
                  </div>
                </div>
                <div style={{ marginTop: "10px", background: "white" }}>
                  <div style={{ height: "10px" }}></div>
                  <div className={styles.formItem}>
                    <Row >
                      <Col span={22} >
                        {/* <Form.Item name="source" label="文献出处"
                      rules={ [ { required: true, message: '请输入文献出处', }, ] }> */}
                        {/* <Form name="dynamic_form_item" { ...formItemLayoutWithOutLabel } onFinish={this.handleOk}> */}
                        <Form.List name="names" initialValue={initvalue}>

                          {(fields, { add, remove }, { errors }) => (
                            <>
                              {fields.map((field, index) => (
                                <Form.Item
                                  name={`name${index}`}
                                  {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                                  label={index === 0 ? '文献出处' : ''}
                                  required={false}
                                  key={field.key}
                                >
                                  <Form.Item
                                    {...field}
                                    validateTrigger={['onChange', 'onBlur']}
                                    rules={[
                                      {
                                        required: true,
                                        whitespace: true,
                                        message: "请输入文献出处.",
                                      },
                                    ]}
                                    noStyle
                                  >
                                    <Input placeholder="请输入文献出处" style={{ width: '60%' }} />
                                  </Form.Item>
                                  {fields.length > 1 ? (
                                    <MinusCircleOutlined
                                      className="dynamic-delete-button"
                                      onClick={() => remove(field.name)}
                                    />
                                  ) : null}
                                </Form.Item>
                              ))}
                              <Form.Item>
                                <PlusCircleOutlined onClick={() => add()} style={{ marginLeft: "558px" }} />
                                <Form.ErrorList errors={errors} />
                              </Form.Item>
                            </>
                          )}
                        </Form.List>
                      </Col>
                    </Row>
                  </div>
                </div>
                <div style={{ textAlign: "center", marginTop: "20px" }}>
                  <Button onClick={this.handleCancel}>取消</Button>
                  <Button type="primary" style={{ marginLeft: "20px" }} htmlType="submit" loading={loading} onClick={this.handleOk}>保存</Button>
                </div>
              </div>
            </Form> : ""
        }
      </div>
    )
  }
}

export default CreateForm;